package com.example.service;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.state.ConnectionState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/*
 * @className: LeaderSelectorService
 * @author: chentao
 * @date: 2025/2/24 上午9:05
 * @Version: 1.0
 * @description:
 */
@Service
public class LeaderSelectorService implements LeaderSelectorListener, InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    private LeaderSelector leaderSelector;

    @Resource
    private ZookeeperService zookeeperService;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.leaderSelector = new LeaderSelector(zookeeperService.getCuratorFramework(), "/zk/leader", this);
        this.leaderSelector.start();
    }

    @Override
    public void destroy() throws Exception {
        this.leaderSelector.close();
    }

    /****
     * 获取到leader的操作
     * @param client the client
     * @throws Exception
     */
    @Override
    public void takeLeadership(CuratorFramework client) throws Exception {
        logger.warn("takeLeadership takeLeadership takeLeadership ....");
    }

    /****
     * 状态发生变化的监听
     * @param client the client
     * @param newState the new state
     */
    @Override
    public void stateChanged(CuratorFramework client, ConnectionState newState) {
        logger.warn("stateChanged stateChanged stateChanged ...." + newState);
    }
}
